<template>
  <div>
    <el-card>
    <el-page-header content="创建新闻" icon="" title="新闻管理" />
    <el-form
      ref="newsFormRef"
      :model="newsForm"
      :rules="newsFormRules"
      label-width="80px"
      class="demo-ruleForm"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="newsForm.title" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <editor @inputChange="inputChange" />
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select
          v-model="newsForm.category"
          style="width: 100%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in options"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="封面" prop="cover">
        <Upload :avatar="newsForm.cover" @fileChange="handleChange"></Upload>
      </el-form-item>
      <el-form-item class="btn-right">
        <el-button type="primary" @click="submitForm()"> 提交新闻 </el-button>
      </el-form-item>
    </el-form>
  </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import Upload from '@/components/upload/Upload'
import upload from '@/util/upload'
import editor from '@/components/editor/Editor'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'

const store = useStore()

const router = useRouter()

const newsForm = reactive({
  title: '',
  content: '',
  category: '', // 1最新动态 2典型案例 3通知公告
  cover: '',
  file: null,
  isPublish: 0, // 1未发布 2已发布
  creater: store.state.userInfo.userName
})
const newsFormRef = ref()
const newsFormRules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'blur' }],
  cover: [{ required: true, message: '请上传封面', trigger: 'blur' }]
})

const inputChange = (data) => {
  // console.log(data);
  newsForm.content = data
}
const handleChange = (file) => {
  newsForm.cover = URL.createObjectURL(file)
  // console.log(newsForm.avatar)
  newsForm.file = file
}

const submitForm = () => {
  newsFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log(newsForm)
      const res = await upload('/adminApi/news/add', newsForm)
      if (res.data.code === '0000') {
        ElMessage.success(res.data.msg)
        router.push(`/news-manage/newsList`)
      }
    }
  })
}

const options = [
  // 1最新动态 2典型案例 3通知公告
  { label: '最新动态', value: 1 },
  { label: '典型案例', value: 2 },
  { label: '通知公告', value: 3 }
]
</script>

<style scoped lang="scss">
.el-form {
  margin-top: 50px;
}
.btn-right {
  float: right;
}
</style>
